/******************************************************************************
 * Copyright (c) 2014 - 2016. Danlu.com Co.Ltd. All rights reserved.          *
 ******************************************************************************/

package cn.com.dhc.danlu.activity.coupon;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import java.math.BigDecimal;
import java.util.ArrayList;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonConst.CouponConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.couponview.OnRightItemClick;
import cn.com.dhc.danlu.widget.couponview.filterview.FilterType;
import cn.com.hd.mall.web.webservices.entity.freedom.entity.coupon.ActivityEntity;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.AchieveCouponReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.AchieveCouponResponse;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CalculatePriceUtil.converseAmount;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-09-22 02:21<br/>
 *
 * <p>
 * 领券中心 & 抢经销商红包
 * </p>
 */
public class DealersCouponObtainAdapter extends BaseDealersCouponAdapter<DealersCouponObtainAdapter.ViewHolder> {

    // TODO: 2016/9/23 后期还需要抽取 why
    public DealersCouponObtainAdapter (Context context, FilterType type) {
        super (context, type);
    }

    @Override
    protected DealersCouponObtainAdapter.ViewHolder createHolder (View view) {
        return new ViewHolder (view);
    }

    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public class ViewHolder extends BaseDealersCouponAdapter.BaseDealersCouponHolder {

        public ViewHolder (View itemView) {
            super (itemView);
            initView ();
        }

        public void initView () {
            if (mFilterType == FilterType.dealers_coupon) {
                // 领券中心
                dlYhq.setRightActionIsVisible (VISIBLE, GONE);
            } else {
                // 抢经销商红包
                dlEnvelop.setRightActionIsVisible (VISIBLE, GONE);
            }
        }

        @Override
        public void refreshItemView (int position) {
            ActivityEntity entity = (ActivityEntity) getItemByPos (position);
            String status = entity.getActivityStatus ();
            String amout = CalculatePriceUtil.converseAmount (CommonUtils.fenToYuan (new BigDecimal (entity.getCouponAmt ())).toPlainString ());
            String time = entity.getUseDate () + " 至 " + entity.getExpireDate ();
            // 折叠限制
            ArrayList<String> limits = new ArrayList<> ();
            if (!TextUtils.isEmpty (entity.getDealerLimit ())) {
                limits.add ("限购" + entity.getDealerLimit ());
            }
            if (!TextUtils.isEmpty (entity.getChannelLimit ())) {
                limits.add ("限购" + entity.getChannelLimit ());
            }
            if (!TextUtils.isEmpty (entity.getMerchLimit ())) {
                limits.add ("限购" + entity.getMerchLimit ());
            }
            if (!TextUtils.isEmpty (entity.getPlatformLimit ())) {
                limits.add (entity.getPlatformLimit () + "可用");
            }

            String amtUseLimit = CalculatePriceUtil.converseAmount (CommonUtils.fenToYuan (new BigDecimal (entity.getAmtUseLimit ())).toPlainString ());
            switch (mFilterType) {
                case dealers_coupon:
                    setDealerCoupon (position, entity, status, amout, time, limits, entity.getDealerLimit (), amtUseLimit);
                    break;

                case dealers_envelop:
                    setDealerEnvelope (position, entity, status, amout, time, limits, entity.getDealerLimit (), amtUseLimit);
                    break;
            }
        }

        /**
         * 设置领券中心界面条目显示
         */
        private void setDealerCoupon (int position, ActivityEntity entity, String status, String amout, String time, ArrayList<String> limits, String dealerLimit, String amtUseLimit) {
            if (TextUtils.isEmpty (amtUseLimit) || CalculatePriceUtil.compare (amtUseLimit, "0") == 0) {
                limits.add ("无使用金额限制");
                dlYhq.setQuota ("无使用金额限制");
            } else {
                limits.add (String.format ("满%s元可用", amtUseLimit));
                dlYhq.setQuota (String.format ("满%s元可用", amtUseLimit));
            }
            dlYhq.setOnExpandListener (new CouponExpandListener (position));
            dlYhq.setExpand (mFoldingSet.contains (position));
            dlYhq.setOnRightItemClick (new CouponRightClickListener (entity, getAdapterPosition ()));

            // 刷新当前优惠券状态
            dlYhq.wrapGetStatus (status); // 立即领取 & 已领取 & 已抢完
            dlYhq.setRestrict (dealerLimit); //经销商使用限制
            dlYhq.setActiveTime (time);
            dlYhq.setPrice (amout.equals ("0") ? "优惠券" : amout); // 10.0- > 10
            dlYhq.setLimitDetail (limits);
        }


        /**
         * 设置抢经销商红包界面条目显示
         */
        private void setDealerEnvelope (int position, ActivityEntity entity, String status, String amout, String time, ArrayList<String> limits, String dealerLimit, String amtUseLimit) {
            dlEnvelop.setOnExpandListener (new CouponExpandListener (position));
            dlEnvelop.setOnRightItemClick (new CouponRightClickListener (entity, getAdapterPosition ()));
            dlEnvelop.setExpand (mFoldingSet.contains (position));
            if ("0".equals (amtUseLimit) || TextUtils.isEmpty (amtUseLimit)) {
                limits.add ("无使用金额限制");
            } else {
                limits.add (String.format ("满%s元可用", amtUseLimit));
            }

            // 刷新当前红包状态
            dlEnvelop.wrapGetStatus (status);
            dlEnvelop.setPrice (status.equals (CouponConst.DEALERS_HAS_USED) ? amout : "红包");
            dlEnvelop.setLimitDetail (limits);
            dlEnvelop.setActiveTime (time);
            dlEnvelop.setQuota (dealerLimit); // 设置XXX经销商发放
        }

        /**
         * 视图右测点击事件监听
         */
        private class CouponRightClickListener implements OnRightItemClick {
            private ActivityEntity entity;
            private int pos;

            CouponRightClickListener (ActivityEntity entity, int pos) {
                this.entity = entity;
                this.pos = pos;
            }

            @Override
            public void onRightItemClick (View view, int resId) {
                String activityStatus = entity.getActivityStatus (); //01-可领取 02-已领取 03-已领完 04-已过期 | 可抢
                if (resId == R.id.sv_right && activityStatus.equals (CouponConst.DEALERS_NOT_USE)) {
                    int tips = mFilterType == FilterType.dealers_coupon ? R.string.obtain_couponing : R.string.obtain_envelop;
                    String token = agent.getToken ();
                    agent.getApi ().achieveCoupon (new AchieveCouponReq (token, entity.getActivityId ()))
                            .compose (OperatorUtils.<AchieveCouponResponse>defaultSchedulers ())
                            .subscribe (new GeneralBusinessObserver<AchieveCouponResponse> (view.getContext (), tips) {
                                @Override
                                protected void onSuccess (AchieveCouponResponse model) {

                                    // 刷新指定item项目
                                    String amout = CommonUtils.fenToYuan (new BigDecimal (model.getCouponAmt ())).toPlainString ();

                                    // 抢券接口红包新增“剩余领用次数”字段：leftTimes，抢红包成功后，若发现次字段的值大于0， 则表示可以再次抢，app可以根据此做样式调整。 lyf 2016-11-02 11:27:41
                                    if (mFilterType == FilterType.dealers_coupon) {
                                        entity.setActivityStatus (CouponConst.DEALERS_HAS_USED);
                                    } else if (mFilterType == FilterType.dealers_envelop) {
                                        // 红包有可领取的次数，当次数为0时，才进行 item 刷新
                                        if (Integer.parseInt (model.getLeftTimes ()) == 0) {
                                            entity.setActivityStatus (CouponConst.DEALERS_HAS_USED);
                                        }
                                    }

                                    // 如果原来对象中此处为空，没有值，则这里将实际获得的金额设置近原来的对象中并刷新界面 lyf
                                    if (TextUtils.isEmpty (entity.getCouponAmt ())) {
                                        entity.setCouponAmt (amout);
                                    }
                                    refreshItem (pos);

                                    String res;
                                    if (mFilterType == FilterType.dealers_coupon) {
                                        res = converseAmount (amout) + "元优惠券领取成功\n请到我的优惠券查看";
                                    } else {
                                        res = "抢到" + converseAmount (amout) + "元红包\n请到经销商红包查看";
                                    }
                                    ToastUtil.getInstance ().show (res, null, false);
                                }

                                @Override
                                protected String parseBussinessException (String code) {
                                    String tips;
                                    if (code.equals (CouponConst.DEALERS_OBTAIN_FINISHED)) {
                                        entity.setActivityStatus (CouponConst.DEALERS_OUT_DATE);
                                        refreshItem (pos);
                                        tips = mFilterType == FilterType.dealers_coupon ? "优惠券已经领完" : "抱歉，红包已抢完请尝试抢其他红包";
                                    } else {
                                        tips = mFilterType == FilterType.dealers_coupon ? "领取失败" : "未抢到该红包";
                                    }
                                    return tips;
                                }

                                @Override
                                protected void onAlertTips (String displayMessage) {
                                    ToastUtil.getInstance ().show (displayMessage, null, false);
                                }
                            });
                }
            }
        }
    }
}